package com.qyzmt.service.impl;

import com.qyzmt.service.AIassistantService;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

@Service
public class AIassistantServiceImpl implements AIassistantService {
    @Override
    public String aiQuestion(String question) {
        String SystemQuestion = "输出不要带任何markdown格式，并且尽量简要回答。除非用户明确要求你详细回答。另外，回答中不要带换行。";
        String content = "尚无内容";
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(30))
                .build();

        String apiUrl = "https://api.deepseek.com/chat/completions";

        String requestBody = "{"
                + "\"model\": \"deepseek-chat\","
                + "\"messages\": [{\"role\": \"system\", \"content\": \" " + SystemQuestion  + " \"},{\"role\": \"user\", \"content\": \" " + question  + " \"}],"
                + "\"stream\": false"
                + "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer sk-8eaa9826aabf4fc3818da8ca385ce32e")
                .header("Accept", "application/json")
                .timeout(Duration.ofSeconds(30))
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status Code: " + response.statusCode());

            if (response.statusCode() == 200) {
                // 简单字符串处理提取回复内容
                String responseBody = response.body();
                content = responseBody.split("\"content\":\"")[1].split("\"")[0];
                System.out.println("\n=== 助手回复 ===");
                System.out.println(content);
            } else {
                System.out.println("AI请求失败: " + response.body());
                content = "请求异常！请联系管理员" + response.body().toString();
            }

        } catch (Exception e) {
            System.err.println("AI请求异常：");
            content = "请求异常！请联系管理员";
            e.printStackTrace();
        }


        return content;




    }
}
